#include "mysqlconnectionpool.h"
#include "asyncservice.h"
#include "databaseservice.h"
#include <boost/bind.hpp>

DatabaseService::DatabaseService(AsyncService &service) :
    m_service(service)
{

}

DatabaseService::~DatabaseService()
{

}

int DatabaseService::init(const std::string &db,
                          const std::string &host,
                          const std::string &user,
                          const std::string &password,
                          unsigned short port)
{
    if(m_pool.get()){
        return boost::system::errc::file_exists;
    }

    m_pool = PoolPtr(new MysqlConnectionPool(db, host, user, password, port));

    if(!m_pool.get()){
        return boost::system::errc::not_enough_memory;
    }

    return 0;
}

void DatabaseService::operation(Implement &&impl)
{
    m_service.post
            (
                boost::bind
                (
                    &DatabaseService::implementation,
                    this,
                    Implement(impl)
                )
            );
}

void DatabaseService::implementation(Implement impl)
{
    try{
        mysqlpp::Connection *c = m_pool->safe_grab();

        impl(c);

        if(c){
            m_pool->release(c);
        }
    }catch(std::exception &){
        exit(-1);
    }
}
